<template>
  <view class="fu-sku" :class="{ 'is-visible': show }">
    <!-- 遮罩层 -->
    <view 
      class="fu-sku__overlay"
      @tap="onClose"
    ></view>
    
    <!-- 内容区域 -->
    <view class="fu-sku__content">
      <!-- 商品信息区域 -->
      <view class="fu-sku__header">
        <image 
          class="fu-sku__image" 
          :src="currentImage || goods.image" 
          mode="aspectFill"
          @tap="previewImage"
        />
        <view class="fu-sku__info">
          <view class="fu-sku__price">
            <text class="fu-sku__price-symbol">¥</text>
            <text class="fu-sku__price-integer">{{ displayPrice.integer }}</text>
            <text class="fu-sku__price-decimal">.{{ displayPrice.decimal }}</text>
          </view>
          <view class="fu-sku__stock">库存 {{ currentStock }} 件</view>
          <view class="fu-sku__selected">已选：{{ selectedText }}</view>
        </view>
        <!-- 关闭按钮 -->
        <view class="fu-sku__close" @tap="onClose">
          <fu-icon name="close" size="40" color="#999"></fu-icon>
        </view>
      </view>
      
      <!-- 规格选择区域 -->
      <scroll-view 
        class="fu-sku__body"
        scroll-y
      >
        <view 
          class="fu-sku__group"
          v-for="(spec, index) in specs"
          :key="index"
        >
          <view class="fu-sku__group-title">{{ spec.name }}</view>
          <view class="fu-sku__options">
            <view
              v-for="(option, optionIndex) in spec.values"
              :key="optionIndex"
              class="fu-sku__option"
              :class="{
                'is-selected': isSelected(spec.name, option),
                'is-disabled': !isAvailable(spec.name, option)
              }"
              @tap="selectOption(spec.name, option)"
            >
              {{ option }}
            </view>
          </view>
        </view>
        
        <!-- 购买数量 -->
        <view class="fu-sku__group">
          <view class="fu-sku__group-title">购买数量</view>
          <view class="fu-sku__stepper">
            <fu-number-box
              v-model="quantity"
              :min="1"
              :max="currentStock"
              :disabled="!isSkuSelected"
            ></fu-number-box>
          </view>
        </view>
      </scroll-view>
      
      <!-- 底部按钮 -->
      <view class="fu-sku__footer">
        <view class="fu-sku__footer-buttons">
          <!-- 加入购物车按钮 -->
          <view 
            class="fu-sku__btn fu-sku__btn--cart"
            :class="{ 'is-disabled': !canSubmit }"
            @tap="onAddToCart"
          >
            <fu-icon name="cart" size="40" color="currentColor"></fu-icon>
            <text>加入购物车</text>
          </view>
          
          <!-- 立即购买按钮 -->
          <view 
            class="fu-sku__btn fu-sku__btn--buy"
            :class="{ 'is-disabled': !canSubmit }"
            @tap="onBuyNow"
          >
            立即购买
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
/**
 * @description SKU 选择器组件
 * @property {Boolean} show 是否显示
 * @property {Object} goods 商品信息
 * @property {Array} specs 规格列表
 * @property {Array} skus SKU 列表
 * @property {Number} contentHeight 内容区域高度
 * @event {Function} close 关闭时触发
 * @event {Function} confirm 确认选择时触发
 */
export default {
  name: 'FuSku',
  
  props: {
    // 是否显示
    show: {
      type: Boolean,
      default: false
    },
    // 商品信息
    goods: {
      type: Object,
      default: () => ({})
    },
    // 规格列表
    specs: {
      type: Array,
      default: () => []
    },
    // SKU 列表
    skus: {
      type: Array,
      default: () => []
    },
    // 内容区域高度
    contentHeight: {
      type: Number,
      default: 800
    }
  },
  
  data() {
    return {
      // 已选规格
      selected: {},
      // 购买数量
      quantity: 1,
      // 当前 SKU 图片
      currentImage: '',
      // 当前库存
      currentStock: 0,
      // 当前价格
      currentPrice: 0
    }
  },
  
  computed: {
    // 显示价格
    displayPrice() {
      const price = this.currentPrice || this.goods.price || 0
      const [integer, decimal = '00'] = price.toFixed(2).split('.')
      return {
        integer,
        decimal
      }
    },
    
    // 已选文本
    selectedText() {
      if (!this.isSkuSelected) {
        return '请选择规格'
      }
      return Object.values(this.selected).join('，')
    },
    
    // 是否已选择完整 SKU
    isSkuSelected() {
      return this.specs.every(spec => this.selected[spec.name])
    },
    
    // 是否可以提交
    canSubmit() {
      return this.isSkuSelected && this.currentStock > 0
    }
  },
  
  watch: {
    show(val) {
      if (val) {
        // #ifdef H5
        document.body.style.overflow = 'hidden'
        document.body.style.position = 'fixed'
        document.body.style.width = '100%'
        // #endif
        
        // #ifdef APP-PLUS
        plus.webview.currentWebview().setStyle({
          bounce: 'none'
        })
        // #endif
        
        this.currentStock = this.goods.stock
        this.currentPrice = this.goods.price
      } else {
        // #ifdef H5
        document.body.style.overflow = ''
        document.body.style.position = ''
        document.body.style.width = ''
        // #endif
        
        // #ifdef APP-PLUS
        plus.webview.currentWebview().setStyle({
          bounce: 'vertical'
        })
        // #endif
        
        this.selected = {}
        this.quantity = 1
        this.currentImage = ''
        this.currentStock = 0
        this.currentPrice = 0
      }
    }
  },
  
  // 组件销毁时确保恢复页面滚动
  beforeDestroy() {
    // #ifdef H5
    document.body.style.overflow = ''
    document.body.style.position = ''
    document.body.style.width = ''
    // #endif
    
    // #ifdef APP-PLUS
    plus.webview.currentWebview().setStyle({
      bounce: 'vertical'
    })
    // #endif
  },
  
  methods: {
    // 关闭
    onClose() {
      this.$emit('close')
    },
    
    // 预览图片
    previewImage() {
      const urls = [this.currentImage || this.goods.image]
      uni.previewImage({
        urls,
        current: urls[0]
      })
    },
    
    // 判断选项是否已选中
    isSelected(specName, option) {
      return this.selected[specName] === option
    },
    
    // 判断选项是否可选
    isAvailable(specName, option) {
      // 获取其他已选规格
      const otherSpecs = { ...this.selected }
      delete otherSpecs[specName]
      
      // 判断是否有可用 SKU
      return this.skus.some(sku => {
        // 检查其他规格是否匹配
        const matchOther = Object.entries(otherSpecs).every(([key, value]) => {
          return sku.specs[key] === value
        })
        
        // 检查当前规格是否匹配且有库存
        return matchOther && sku.specs[specName] === option && sku.stock > 0
      })
    },
    
    // 选择规格选项
    selectOption(specName, option) {
      if (!this.isAvailable(specName, option)) return
      
      // 更新选中状态
      this.selected = {
        ...this.selected,
        [specName]: option
      }
      
      // 更新 SKU 信息
      this.updateCurrentSku()
    },
    
    // 更新当前 SKU 信息
    updateCurrentSku() {
      if (!this.isSkuSelected) return
      
      // 查找匹配的 SKU
      const currentSku = this.skus.find(sku => {
        return Object.entries(this.selected).every(([key, value]) => {
          return sku.specs[key] === value
        })
      })
      
      if (currentSku) {
        this.currentImage = currentSku.image
        this.currentStock = currentSku.stock
        this.currentPrice = currentSku.price
        
        // 调整数量
        if (this.quantity > currentSku.stock) {
          this.quantity = currentSku.stock
        }
      }
    },
    
    // 加入购物车
    onAddToCart() {
      if (!this.canSubmit) return
      
      this.$emit('add-cart', {
        selected: this.selected,
        quantity: this.quantity,
        sku: this.skus.find(sku => {
          return Object.entries(this.selected).every(([key, value]) => {
            return sku.specs[key] === value
          })
        })
      })
    },
    
    // 立即购买
    onBuyNow() {
      if (!this.canSubmit) return
      
      this.$emit('buy-now', {
        selected: this.selected,
        quantity: this.quantity,
        sku: this.skus.find(sku => {
          return Object.entries(this.selected).every(([key, value]) => {
            return sku.specs[key] === value
          })
        })
      })
    }
  }
}
</script>

<style lang="scss">
.fu-sku {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 999;
  visibility: hidden;
  
  &.is-visible {
    visibility: visible;
    
    .fu-sku__overlay {
      opacity: 1;
    }
    
    .fu-sku__content {
      transform: translateY(0);
    }
  }
  
  &__overlay {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
    opacity: 0;
    transition: opacity 0.3s;
  }
  
  &__content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    border-radius: 32rpx 32rpx 0 0;
    transform: translateY(100%);
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    display: flex;
    flex-direction: column;
    max-height: 90vh;
    overflow: hidden;
  }
  
  &__close {
    position: absolute;
    right: 20rpx;
    top: 20rpx;
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    &:active {
      opacity: 0.7;
    }
  }
  
  &__header {
    position: relative;
    flex-shrink: 0;
    display: flex;
    padding: 30rpx;
    background: #fff;
    
    &::after {
      content: '';
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      height: 2rpx;
      background: linear-gradient(to right, rgba(0,0,0,0.02), rgba(0,0,0,0.05), rgba(0,0,0,0.02));
    }
  }
  
  &__image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 20rpx;
    margin-right: 24rpx;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  }
  
  &__info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  
  &__price {
    color: #ff4444;
    margin-bottom: 12rpx;
    
    &-symbol {
      font-size: 32rpx;
    }
    
    &-integer {
      font-size: 48rpx;
      font-weight: bold;
    }
    
    &-decimal {
      font-size: 32rpx;
    }
  }
  
  &__stock {
    font-size: 26rpx;
    color: #999;
    margin-bottom: 12rpx;
  }
  
  &__selected {
    font-size: 28rpx;
    color: #333;
  }
  
  &__body {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    // 添加弹性滚动效果
    overscroll-behavior: contain;
  }
  
  &__group {
    padding: 30rpx;
    
    &:not(:last-child) {
      position: relative;
      
      &::after {
        content: '';
        position: absolute;
        left: 30rpx;
        right: 30rpx;
        bottom: 0;
        height: 2rpx;
        background: #f5f5f5;
      }
    }
  }
  
  &__group-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 24rpx;
    font-weight: 500;
  }
  
  &__options {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -8rpx;
  }
  
  &__option {
    min-width: 120rpx;
    height: 68rpx;
    padding: 0 32rpx;
    margin: 8rpx;
    border-radius: 34rpx;
    font-size: 28rpx;
    color: #333;
    background-color: #f7f7f7;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    
    &.is-selected {
      color: #ff4444;
      background-color: #fff0f0;
      font-weight: 500;
      box-shadow: 0 0 0 2rpx #ff4444;
    }
    
    &.is-disabled {
      color: #ccc;
      background-color: #f7f7f7;
      
      &:active {
        opacity: 1;
      }
    }
    
    &:active {
      opacity: 0.7;
    }
  }
  
  &__stepper {
    display: flex;
    align-items: center;
  }
  
  &__footer {
    flex-shrink: 0;
    position: relative;
    padding: 20rpx 30rpx calc(20rpx + env(safe-area-inset-bottom));
    background-color: #fff;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      height: 2rpx;
      background: linear-gradient(to right, transparent, #f5f5f5, transparent);
    }
  }
  
  &__footer-buttons {
    display: flex;
    gap: 20rpx;
  }
  
  &__btn {
    height: 88rpx;
    border-radius: 44rpx;
    font-size: 30rpx;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    
    &--cart {
      flex: 0.8;
      background-color: #fff0f0;
      color: #ff4444;
      gap: 8rpx;
      
      &.is-disabled {
        opacity: 0.5;
      }
    }
    
    &--buy {
      flex: 1.2;
      background: linear-gradient(135deg, #ff4444, #ff1111);
      color: #fff;
      
      &.is-disabled {
        opacity: 0.5;
      }
    }
    
    &:active {
      transform: scale(0.98);
    }
  }
}
</style> 